package com.example.jdshopdeail;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.collection.ArrayMap;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;

import com.example.jdshopdeail.adapter.ViewPagerAdapter;
import com.example.jdshopdeail.base.BaseActivity;
import com.example.jdshopdeail.bean.CartComputeBean;
import com.example.jdshopdeail.bean.ShopDetailBean;
import com.example.jdshopdeail.fragment.FMBadyDetail;
import com.example.jdshopdeail.fragment.FMCommonList;
import com.example.jdshopdeail.fragment.FMProductCase;
import com.example.jdshopdeail.impl.CartImpl;
import com.example.jdshopdeail.impl.UserImpl;
import com.example.jdshopdeail.util.GlideImageLoader;
import com.example.jdshopdeail.util.ParseUtils;
import com.example.jdshopdeail.util.ScreenUtil;
import com.example.jdshopdeail.util.StatusBarUtils;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.tabs.TabLayout;
import com.jaeger.library.StatusBarUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class MainActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.shop_banner)
    Banner shopBanner;
    @BindView(R.id.shop_tablayout)
    TabLayout shopTablayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.shop_title_tv)
    TextView shopTitleTv;
    @BindView(R.id.shop_name_tv)
    TextView shopNameTv;
    @BindView(R.id.shop_price_tv)
    TextView shopPriceTv;
    @BindView(R.id.shop_vip_price_tv)
    TextView shopVipPriceTv;
    @BindView(R.id.shop_specif_tv)
    TextView shopSpecifTv;
    @BindView(R.id.sales_volume_tv)
    TextView salesVolumeTv;
    @BindView(R.id.coupon_tv)
    TextView couponTv;
    @BindView(R.id.coupon_content_tv)
    TextView couponContentTv;
    @BindView(R.id.coupon_next_iv)
    ImageView couponNextIv;
    @BindView(R.id.coupon_rl)
    RelativeLayout couponRl;
    @BindView(R.id.promotions_tv)
    TextView promotionsTv;
    @BindView(R.id.promotions_content_tv)
    TextView promotionsContentTv;
    @BindView(R.id.promotions_next_iv)
    ImageView promotionsNextIv;
    @BindView(R.id.promotions_rl)
    RelativeLayout promotionsRl;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.cart_tv)
    TextView cartTv;
    @BindView(R.id.service_tv)
    TextView serviceTv;
    @BindView(R.id.collection_tv)
    TextView collectionTv;
    @BindView(R.id.ll_head)
    LinearLayout llHead;
    @BindView(R.id.add_cart_btn)
    Button addCartBtn;
    @BindView(R.id.buy_now_btn)
    Button buyNowBtn;
    @BindView(R.id.al_shop_detail)
    AppBarLayout alShopDetail;
    @BindView(R.id.coll_toolbar_layout)
    CollapsingToolbarLayout collToolbarLayout;
    @BindView(R.id.content_cl)
    ConstraintLayout contentCl;
    @BindView(R.id.tv_home_statusbar)
    TextView tvHomeStatusbar;
    @BindView(R.id.nsv_good)
    NestedScrollView nsvGood;
    @BindView(R.id.ll_cart)
    LinearLayout llCart;
    CoordinatorLayout clGood;
    @BindView(R.id.tv_cart_count)
    TextView tvCartCount;
    @BindView(R.id.tv_take_name)
    TextView tvTakeName;
    @BindView(R.id.tv_year)
    TextView tvYear;
    @BindView(R.id.tv_mouth)
    TextView tvMouth;
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.rl_take)
    RelativeLayout rlTake;
/*    @BindView(R.id.sw_shop)
    SwipeRefreshLayout swipeRefreshLayout;*/

    private List<Fragment> list;
    private int mAlpha;
    private ShopDetailBean detailModel;
    private FMCommonList fmCommonList = new FMCommonList();
    private FMProductCase fmProductCase = new FMProductCase();
    private FMBadyDetail fmBadyDetail = new FMBadyDetail();
    private int goodCount;
    private boolean isBottom;
    private boolean isCollect = false;
    private AlertDialog addDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    protected void initView() {
        toolbar.setTitle("");
        setStatusBar(tvHomeStatusbar);
        viewPager.setOffscreenPageLimit(3);
        setSupportActionBar(toolbar);
        initToolBar();
        initScrollView();
        initBanner();
        initTabLayout();
    }

    private void initBanner() {
        List<String> list = new ArrayList<>();
        list.add("http://ww4.sinaimg.cn/large/006uZZy8jw1faic21363tj30ci08ct96.jpg");
        list.add("http://ww4.sinaimg.cn/large/006uZZy8jw1faic259ohaj30ci08c74r.jpg");
        list.add("http://ww4.sinaimg.cn/large/006uZZy8jw1faic2b16zuj30ci08cwf4.jpg");
        list.add("http://ww4.sinaimg.cn/large/006uZZy8jw1faic2e7vsaj30ci08cglz.jpg");

        //设置banner样式
        shopBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        shopBanner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        shopBanner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        shopBanner.isAutoPlay(true);
        //设置轮播时间
        shopBanner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        shopBanner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        shopBanner.setImages(list);
        shopBanner.start();
    }

    private void initScrollView() {
        //监听AppBarLayout滑动状态
        alShopDetail.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {

            if (appBarLayout.getTotalScrollRange() == -verticalOffset) {
                if (isBottom) {
                } else {
                    isBottom = true;
                }
            } else {
                isBottom = false;
            }
            int minHeight = 50;
            if (shopBanner != null && shopBanner.getMeasuredHeight() != 0) {
                int maxHeight = shopBanner.getMeasuredHeight() / 2;
                if (maxHeight == 0) {
                    maxHeight = 255;
                }
                if (Math.abs(verticalOffset) <= minHeight) {
                    mAlpha = 0;
                } else if (Math.abs(verticalOffset) > maxHeight) {
                    mAlpha = 255;
                } else {
                    mAlpha = (Math.abs(verticalOffset) - minHeight) * 200 / (maxHeight - minHeight);
                }
                if (mAlpha <= 0) {
                    llHead.setBackgroundColor(Color.argb(0, 255, 255, 255));
                } else if (mAlpha >= 255) {
                    llHead.setBackgroundColor(Color.argb(mAlpha, 200,200,150));
                } else {
                    llHead.setBackgroundColor(Color.argb(mAlpha, 200, 200, 150));
                }
            }
        });
    }

    private void initTabLayout() {
        list = new ArrayList<>();
        list.add(fmBadyDetail);//宝贝详情
        list.add(fmProductCase);//产品案例
        list.add(fmCommonList);//商品评价
        ViewPagerAdapter vpAdapter = new ViewPagerAdapter(getSupportFragmentManager(), list);
        viewPager.setAdapter(vpAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener
                (shopTablayout));
        shopTablayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener
                (viewPager));
    }


    @Override
    protected void addListener() {
/*        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                },2000);
            }
        });
        swipeRefreshLayout.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

            }
        });*/
    }

    private void initToolBar() {

    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.setTranslucentForImageView(MainActivity.this, 0, null);
        StatusBarUtils.StatusBarLightMode(this, StatusBarUtils.StatusBarLightMode(this));
    }

    /**
     * 加入购物车
     * 由于没有接口,所以数量缓存有问题,小伙伴们看效果就好了
     */
    @SuppressLint("SetTextI18n")
    private void showAddCartDialog(final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
        addDialog = builder.show();
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_add_cart, null);
        WindowManager.LayoutParams params = addDialog.getWindow().getAttributes();
        params.width = ScreenUtil.getScreenWidth(this);
        //主动弹出输入法键盘
        addDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        addDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        addDialog.getWindow().setGravity(Gravity.BOTTOM);
        addDialog.getWindow().setAttributes(params);
        addDialog.getWindow().setContentView(view);
        addDialog.setCanceledOnTouchOutside(true);
        addDialog.setCancelable(true);
        final TextView clearTv = view.findViewById(R.id.clear_tv);
        final ImageView addBtn = view.findViewById(R.id.add_count_btn);
        final ImageView minusBtn = view.findViewById(R.id.minus_count_btn);
        final Button finishBtn = view.findViewById(R.id.finish_btn);
        final EditText cartCount = view.findViewById(R.id.edit_count);
        final RelativeLayout rlAdd = view.findViewById(R.id.rl_add);
        cartCount.setSelection(getTV(cartCount).length());
        finishBtn.setOnClickListener(v -> addDialog.dismiss());
        final int count = ParseUtils.parseInt(cartCount.getText().toString());
        if (count <= 1) {
            cartCount.setClickable(false);
            minusBtn.setBackgroundResource(R.mipmap.minus_grey);
        } else {
            minusBtn.setBackgroundResource(R.mipmap.minus);
        }
        minusBtn.setOnClickListener(v -> {
            int count1 = ParseUtils.parseInt(cartCount.getText().toString());
            if (count1 > 1) {
                count1--;
                cartCount.setText(count1 + "");
                cartCount.setSelection(cartCount.length());
                if (count1 == 1) {
                    cartCount.setClickable(false);
                    minusBtn.setBackgroundResource(R.mipmap.minus_grey);
                }
            } else {
                cartCount.setClickable(false);
                cartCount.setSelection(cartCount.length());
                minusBtn.setBackgroundResource(R.mipmap.minus_grey);
            }
        });
        addBtn.setOnClickListener(v -> {
            int count12 = ParseUtils.parseInt(cartCount.getText().toString());
            count12++;
            cartCount.setText(count12 + "");
            cartCount.setClickable(true);
            cartCount.setSelection(cartCount.length());
            minusBtn.setBackgroundResource(R.mipmap.minus);
        });
        clearTv.setOnClickListener(v -> {
            cartCount.setText(count + "");
            cartCount.setSelection(cartCount.length());
        });
        cartCount.setFocusableInTouchMode(true);

        finishBtn.setOnClickListener(v -> {
            addDialog.dismiss();
        /*    if (detailModel == null || ParseUtils.parseInt(detailModel.getGoods_number()) <= 0) {
                showToast("商品已售罄");
                return;
            }
*/
            int count13 = ParseUtils.parseInt(getTV(cartCount));
            if (count13 <= 0) {
                showToast("请输入正确的数量");
                return;
            }

            if (type == 1) {
                CartImpl.addCart(detailModel, ParseUtils.parseInt(getTV(cartCount)));
                upDateCartNumber();
                showToast("加入成功");
            } else {
                if (detailModel != null) {
                    List<CartComputeBean> computeModels = new ArrayList<>();
                    CartComputeBean m = new CartComputeBean();
                    m.setGood_id(detailModel.getGoods_id());
                    goodCount = ParseUtils.parseInt(getTV(cartCount));
                    m.setGood_count(goodCount + "");
                    computeModels.add(m);
                }
            }
        });
        rlAdd.setOnClickListener(v -> addDialog.dismiss());
    }


    private void upDateCartNumber() {
        if (tvCartCount == null) {
            return;
        }
        int count = CartImpl.getCartSize();
        if (count == 0) {
            tvCartCount.setVisibility(View.GONE);
        } else {
            tvCartCount.setVisibility(View.VISIBLE);
            tvCartCount.setText(count > 99 ? "99+" : count + "");
        }
    }

    /**
     * 商品是否已收藏
     *
     * @param goods_id
     */
    private void getIsCollect(String goods_id) {
        ArrayMap<String, String> map = new ArrayMap<>();
        map.put("user_id", UserImpl.getUserId());
        map.put("ele_id", goods_id);
        map.put("collert_id", "0");
        map.put("type", "1");

    }

    @OnClick({R.id.coupon_rl, R.id.promotions_rl, R.id.cart_tv, R.id.service_tv, R.id.collection_tv, R.id.add_cart_btn, R.id.buy_now_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.coupon_rl:
                //showCouponDialog();//领优惠券
                break;
            case R.id.promotions_rl:
                //showPromotionsDialog();//促销活动
                break;
            case R.id.cart_tv:
                break;
            case R.id.add_cart_btn://加入购物车
                showAddCartDialog(1);
                break;
            case R.id.buy_now_btn://立即购买
                showAddCartDialog(2);
                break;
            case R.id.service_tv://客服
                break;
            case R.id.collection_tv://收藏商品
                if (isCollect) {
                    //请求取消收藏接口
                } else {
                  //获取收藏列表接口
                }
                break;
        }
    }
}